package com.cskaoyan.service.admin.goods.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.admin.goods.CreatBO;
import com.cskaoyan.bean.bo.admin.goods.UpdeleteGoodsBO;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.admin.goods.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.admin.goods.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.Tang
 * @since 2022/09/06 23:29
 */
@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    MarketBrandMapper marketBrandMapper;
    @Autowired
    MarketGoodsProductMapper marketProductMapper;
    @Autowired
    MarketGoodsSpecificationMapper marketSpecificationMapper;
    @Autowired
    MarketGoodsAttributeMapper marketAttributeMapper;
    /**
     * TODO 查找所有商品界面
     * @param basePageInfo
     * @return
     */
    @Override
    public CommonData selectGoodsInfo(BasePageInfo basePageInfo,Integer goodsId,Integer goodsSn,String name) {

      if(basePageInfo.getLimit() == 0) {
          basePageInfo.setLimit(1000);
      }
      if(basePageInfo.getPage() == null || basePageInfo.getPage() == 0){
          basePageInfo.setPage(1);
      }


        // 分页拿到请求参数中的分页信息1和信息条数20
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());

        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        // 添加升序排列条件，DESC为降序
        marketGoodsExample.setOrderByClause(basePageInfo.getSort()+" "+basePageInfo.getOrder());
        // 判断查询条件
        if(!StringUtils.isEmpty(goodsId)){
            criteria.andIdEqualTo(goodsId);
        }
        if(!StringUtils.isEmpty(goodsSn)){
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        if(!StringUtils.isEmpty(name)){
            criteria.andNameLike("%"+name+"%");
        }
        if(basePageInfo.getLimit() == 1000 && basePageInfo.getPage() == 1) {
            marketGoodsExample = null;
        }
        // 查询到所有商品信息
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);



        // 把查询出来的结果放进去，使用PageInfo包装查询后的结果，只需要将PageInfo交给页面就行
        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(marketGoods);
        return CommonData.data(marketGoodsPageInfo);
        }






    /**
     * 添加商品显示页面
     * 响应为两个list
     *   List<CategoryListEntityOfCatAndBrandVO> categoryList;
     *   List<BrandListEntityOfCatAndBrandVO> brandList;
     * @return
     */
    @Override
    public CatAndBrandVO selectCateAndBrand() {
        // 1. 先处理第一个list响应
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        MarketCategoryExample.Criteria criteria = marketCategoryExample.createCriteria();
        // 查询pid为0的信息
        criteria.andPidEqualTo(0);
        // 设置逻辑删除为deleted=false这个条件下，做筛选
        criteria.andDeletedEqualTo(false);
        List<MarketBrand> marketBrandList = null;
        CatAndBrandVO catAndBrandVO = new CatAndBrandVO();
        // 用category的实类接收查询到的数据
        List<MarketCategory> marketCategoryList = marketCategoryMapper.selectByExample(marketCategoryExample);
        // 2. 处理第二个list响应
        MarketBrandExample brandExample = new MarketBrandExample();
        brandExample.createCriteria().andDeletedEqualTo(false);
        marketBrandList = marketBrandMapper.selectByExample(brandExample);

        // 3. 响应汇总并封装为VO

        catAndBrandVO = catAndBrandPOToVO(marketCategoryList,marketBrandList);

        return catAndBrandVO;
    }


    /**
     * 新增商品
     * @param creatBO
     * 逻辑：分别插入四张表
     */
    @Override
    public void insertCreatBO(CreatBO creatBO) {

        // 插入goods表
       MarketGoods goods = creatBO.getGoods();
        marketGoodsMapper.insertSelective(goods);
        // 拿到goodsid对接下来的list做处理
        Integer id = goods.getId();

        // 岔路Attributes表
        List<MarketGoodsAttribute> attributes = creatBO.getAttributes();
        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(id);
            marketAttributeMapper.insertSelective(attribute);
        }

        // 插入product表
        List<MarketGoodsProduct> products = creatBO.getProducts();


        for (MarketGoodsProduct product : products) {
            product.setGoodsId(id);
            marketProductMapper.insertSelective(product);
        }
        // 插入specification表
        List<MarketGoodsSpecification> specifications = creatBO.getSpecifications();
        for (MarketGoodsSpecification specification : specifications) {
            specification.setGoodsId(id);
            marketSpecificationMapper.insertSelective(specification);
        }
    }


    /**
     * 删除商品
     * @param marketGoods
     */
    @Override
    public void deleteForGoods(MarketGoods marketGoods) {
        marketGoods.setDeleted(true);
        marketGoodsMapper.updateByPrimaryKeySelective(marketGoods);
    }

    /**
     * 更新商品
     * @param updeleteGoodsBO
     */
    @Override
    public void updateForGoods(UpdeleteGoodsBO updeleteGoodsBO) {
        //1.首先更新goods表的信息
        MarketGoods goods = updeleteGoodsBO.getGoods();
        marketGoodsMapper.updateByPrimaryKeySelective(goods);
        Integer id = goods.getId();
        //2.更新attributes表的信息
        List<MarketGoodsAttribute> attributes = updeleteGoodsBO.getAttributes();
        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(id);
            marketAttributeMapper.updateByPrimaryKeySelective(attribute);
        }
        //3.更新specification表的信息
        List<MarketGoodsSpecification> specifications = updeleteGoodsBO.getSpecifications();
        for (MarketGoodsSpecification specification : specifications) {
            specification.setGoodsId(id);
            marketSpecificationMapper.updateByPrimaryKeySelective(specification);
        }
        //4.更新specification表的信息
        List<MarketGoodsProduct> products = updeleteGoodsBO.getProducts();
        for (MarketGoodsProduct product : products) {
            product.setGoodsId(id);
            marketProductMapper.updateByPrimaryKeySelective(product);
        }
    }



    /**
     * @description: TODO 查询商品详情
     * @date: 2022/9/8 23:33
     * @param: [id]
     */
    @Override
    public GoodsDetailVo detail(Integer id) {
        // 1. 根据id查找商品详情表
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);
        // 得到图片数组
        String[] gallery = marketGoods.getGallery();
        // 遍历数组，获得宣传画廊的图片url
        for (int i = 0; i < gallery.length; i++) {
            // ["http://yanxuan.nosdn.127.net/4eb09e08ac9de543d2291d27a6be0b54.jpg", "http://yanxuan.nosdn.127.net/0c9eb81c7594dbe42802ff1ebbece51a.jpg", "http://yanxuan.nosdn.127.net/8cfc7b6bfd28687ab3399da08e5ba61b.jpg", "http://yanxuan.nosdn.127.net/b98cfd7f197b62abd1679321eae253a6.jpg"]
            String replaceAll = gallery[i].trim().replaceAll("\"", "");
            gallery[i] = replaceAll;
            System.out.println(replaceAll);
        }

        // 2. 根据id查询商品参数表
        MarketGoodsAttributeExample goodsAttributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria criteria = goodsAttributeExample.createCriteria();
        System.out.println("criteria" + criteria);
        MarketGoodsAttributeExample.Criteria goodsIdEqualTo1 = criteria.andGoodsIdEqualTo(id);
        System.out.println("goodsIdEqualTo" + goodsIdEqualTo1);
        // 查询商品详情表
        List<MarketGoodsAttribute> goodsAttributes = marketAttributeMapper.selectByExample(goodsAttributeExample);

        // 3. 根据id查询商品规格表
        MarketGoodsSpecificationExample goodsSpecificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria goodsIdEqualTo2 = goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> goodsSpecifications = marketSpecificationMapper.selectByExample(goodsSpecificationExample);

        // 4. 根据id查询品牌表
        MarketGoodsProductExample goodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria goodsIdEqualTo3 = goodsProductExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> goodsProducts = marketProductMapper.selectByExample(goodsProductExample);

        // 5. 根据id查询商品类别，和类别id，和 pid
        ArrayList<Integer> arrayList = new ArrayList<>();
        Integer categoryId = marketGoods.getCategoryId();
        MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(categoryId);

        arrayList.add(marketCategory.getPid());
        arrayList.add(marketGoods.getCategoryId());

        MarketGoods goods = new MarketGoods();
        goods.setId(marketGoods.getId());
        goods.setGoodsSn(marketGoods.getGoodsSn());
        goods.setName(marketGoods.getName());
        goods.setCategoryId(marketGoods.getCategoryId());
        goods.setBrandId(marketGoods.getBrandId());
        goods.setGallery(marketGoods.getGallery());
        goods.setKeywords(marketGoods.getKeywords());
        goods.setBrief(marketGoods.getBrief());
        goods.setIsOnSale(marketGoods.getIsOnSale());
        goods.setSortOrder(marketGoods.getSortOrder());
        goods.setPicUrl(marketGoods.getPicUrl());
        goods.setShareUrl(marketGoods.getShareUrl());
        goods.setIsNew(marketGoods.getIsNew());
        goods.setIsHot(marketGoods.getIsHot());
        goods.setUnit(marketGoods.getUnit());
        goods.setCounterPrice(marketGoods.getCounterPrice());
        goods.setRetailPrice(marketGoods.getRetailPrice());
        goods.setAddTime(marketGoods.getAddTime());
        goods.setUpdateTime(marketGoods.getUpdateTime());
        goods.setDeleted(marketGoods.getDeleted());
        goods.setDetail(marketGoods.getDetail());

        // 6. 把查询得到的商品信息封装进GoodsDetailVo中,返回
        GoodsDetailVo detailVo = new GoodsDetailVo();
        detailVo.setAttributes(goodsAttributes);
        detailVo.setSpecifications(goodsSpecifications);
        detailVo.setProducts(goodsProducts);
        detailVo.setGoods(goods);

        return detailVo;
    }


    /**
     * catAndBrand  po -->  vo 的方法
     * @param marketCategoryList
     * @param marketBrandList
     * @return
     */
    private CatAndBrandVO catAndBrandPOToVO(List<MarketCategory> marketCategoryList, List<MarketBrand> marketBrandList) {
       // 1. 处理brandListVo响应
        // new一个总响应对象
        CatAndBrandVO catAndBrandVO = new CatAndBrandVO();
        // new一个brandlist响应对象
        List<BrandListEntityOfCatAndBrandVO> brandListVO = new ArrayList<>();
        // 获取到的二级id数组

        Integer pid = null;
        String pidName = null;
        // 三级查询结果
        Integer id = null;
        String name = null;
        // 转换需要参数

        // 将查询到的brand信息转换为VO
        for (int i = 0; i < marketBrandList.size(); i++) {
            BrandListEntityOfCatAndBrandVO brandListEntityOfCatAndBrandVO = new BrandListEntityOfCatAndBrandVO();
            // 拿到brandId
            Integer brandId = marketBrandList.get(i).getId();
            // 将brandId值转化为value
            brandListEntityOfCatAndBrandVO.setValue(brandId);
            String brandName = marketBrandList.get(i).getName();
            // 将name值转换为lable
            brandListEntityOfCatAndBrandVO.setLabel(brandName);
            // 放入brandlist响应对象中
            brandListVO.add(i,brandListEntityOfCatAndBrandVO);
        }
        // 加入到最高层对象
        catAndBrandVO.setBrandList(brandListVO);

        // 2. 处理CategoryList响应
        // new一个CategoryList响应对象
        List<CategoryListEntityOfCatAndBrandVO> categoryListVO = new ArrayList<>();
        for (int i = 0; i < marketCategoryList.size(); i++) {
            CategoryListEntityOfCatAndBrandVO categoryListEntityOfCatAndBrandVO = new CategoryListEntityOfCatAndBrandVO();
            List<ChildrenEntityOfCategoryListEntityOfCatAndBrandVO> childrenListVO = new ArrayList<>();
            // 设置二级id
            // 拿到pid与pidName
            pid = marketCategoryList.get(i).getId();
            pidName = marketCategoryList.get(i).getName();
            // 将pid转换为value
            categoryListEntityOfCatAndBrandVO.setValue(pid);
            // 将pidName转换为Name
            categoryListEntityOfCatAndBrandVO.setLabel(pidName);
            // 二级id对应的三级信息
            MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
            marketCategoryExample.createCriteria().andPidEqualTo(pid);
            // 查出chilrdren所对应的信息,并封装到第二类孩子类中
            List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(marketCategoryExample);
            for (int j = 0; j < marketCategories.size(); j++) {
                ChildrenEntityOfCategoryListEntityOfCatAndBrandVO children= new ChildrenEntityOfCategoryListEntityOfCatAndBrandVO();
                // 取出id和name
                id = marketCategories.get(j).getId();
                name = marketCategories.get(j).getName();
                // 将id和name设置为lable和value
                children.setValue(id);
                children.setLabel(name);
                childrenListVO.add(children);
            }
            // 将第三个list的信息放入第二个list中，此时已经全部放完
            categoryListEntityOfCatAndBrandVO.setChildren(childrenListVO);
            // 加入到一级list
            categoryListVO.add(i,categoryListEntityOfCatAndBrandVO);

        }
        // 加入到最高层对象
        catAndBrandVO.setCategoryList(categoryListVO);

        return catAndBrandVO;
    }


}
